<template>
  <div>
    <!-- 搜索区域 -->
    <userSearchForm :page="page" :loadData="loadData" />
    <!-- 按钮区域 -->
    <userToolsBtns
      @addUserHandle="addUserHandle"
      :tableData="tableData"
      :selectUserIds="selectUserIds"
      :deleteAllUser="deleteAllUserHandle"
    />
    <!-- 数据表格 -->
    <userTable
      :tableData="tableData"
      :page="page"
      :total="total"
      :loadData="loadData"
      :setSelectUserIds="setSelectUserIds"
      :setDialogVisible="setDialogVisible"
    />
    <!-- 弹出层 -->
    <el-dialog
      :title="userid === 0 ? '新增用户' : '修改用户'"
      :visible.sync="dialogVisible"
      top="60px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <addUserForm v-if="userid === 0" :setDialogVisible="setDialogVisible" />
      <editUserForm v-else :userid="userid" :setDialogVisible="setDialogVisible" />
    </el-dialog>
  </div>
</template>

<script>
import userSearchForm from './ui/userSearchForm.vue'
import userToolsBtns from './ui/userToolsBtns.vue'
import userTable from './ui/userTable.vue'
import addUserForm from './ui/addUserForm.vue'
import editUserForm from './ui/editUserForm.vue'
import { getUsersApi, deleteAllApi } from '@/api/userApi'

export default {
  components: {
    userSearchForm,
    userToolsBtns,
    userTable,
    addUserForm,
    editUserForm
  },
  props: ['page'],
  data() {
    return {
      dialogVisible: false,
      tableData: [],
      selectUserIds: [],
      total: 0,
      userid: 0
    }
  },
  watch: {
    dialogVisible(value) {
      !value && (this.userid = 0)
    }
  },
  mounted() {
    this.loadData(this.page, this.$route.query)
  },
  methods: {
    // 加载用户数据
    async loadData(page = 1, search = null) {
      let ret = await getUsersApi(page, search)
      if (ret.code === 0) {
        this.total = ret.data.total
        this.tableData = ret.data.users
      }
    },
    // 删除选中的用户
    async deleteAllUserHandle(ids) {
      let page = this.page
      // 删除操作
      let ret = await deleteAllApi(ids)
      if (ret.code === 0) {
        // 删除成功,判断是否为全选删除
        if (this.tableData.length == ids.length) {
          if (page != 1) {
            page--
          }
        }
        this.$router.replace({ query: { ...this.$route.query, page } })
        this.loadData(page)
      }
    },
    setSelectUserIds(ids) {
      let uid = this.$store.getters.userid
      ids.splice(ids.indexOf(uid), 1)
      this.selectUserIds = ids
    },
    setDialogVisible(show, userid = 0) {
      this.dialogVisible = show
      // 打开
      if (show) {
        this.userid = userid
      }

      // 关闭弹出层时才进行再次请求数据
      !show && this.loadData()
    },
    addUserHandle(show) {
      this.dialogVisible = show
    }
  }
}
</script>

<style lang="scss" scoped></style>
